import time
import re
from common.pre_config_brower import chrome_brower
from common.download_img import downloadImage
from common.getConfig import logger


class Amazon:
    def __init__(self, url):
        self.driver = chrome_brower(
            headless=False, disableIMG=True, disableJS=False)
        self.home_url = url
        self.main_windows_id = None
        self.open_web()

    # open the web pages
    def open_web(self):
        try:
            self.driver.get(self.home_url)
            self.main_windows_id = self.driver.window_handles[-1]
        except Exception as e:
            print("open the first page failure", e)

    # search the elements, e.g. production name , href, picture and so on
    def get_info_from_page_fmt1(self):
        time.sleep(2)
        self.roll_to_top()
        items_num_info_list = self.driver.find_elements_by_css_selector(
            "[class='sg-col-4-of-12 s-result-item s-asin sg-col-4-of-16 sg-col sg-col-4-of-20']")

        for item in items_num_info_list:
            product = {}
            produce_info = item.find_element_by_css_selector(
                "[class = 'a-link-normal s-no-outline']")
            produce_url = produce_info.get_attribute('href')
            produce_img_name = produce_info.find_element_by_xpath('div/img')
            produce_name = produce_img_name.get_attribute(
                'alt').replace(".", "")
            jpg_url_list = produce_img_name.get_attribute("srcset")
            jpg_url = re.findall(r"(https://.*?.jpg)", jpg_url_list)[-2]

            price_value_item = item.find_elements_by_css_selector(
                "[class='a-price']")
            price_value = "none"
            if price_value_item:
                price_value = price_value_item[0].text.replace("\n", ".")
            # logger.debug("produce_url: %s" % produce_url)
            # logger.debug("price: %s" % price_value)

            product["productName"] = produce_name
            product["productPrice"] = price_value
            product["productUrl"] = produce_url
            product["productImageUrl"] = jpg_url
            product["productImageName"] = downloadImage.format_img_name(
                name=produce_name)
            product["productMore"] = self.__open_new_windows(produce_url)

            # yield jpg_url, produce_name, price_value, produce_url
            yield product

    def get_info_from_page_fmt2(self):
        time.sleep(2)
        self.roll_to_top()
        items_num_info_list = self.driver.find_elements_by_css_selector(
            "[class ^='ProductGridItem__item__']")
        logger.info("the items num of the page: %s" % len(items_num_info_list))

        for item in items_num_info_list:
            product = {}
            jpg_item = item.find_element_by_css_selector(
                "[class ^= 'ProductGridItem__image__']")
            jpg_url_list = jpg_item.find_element_by_xpath(
                "./img").get_attribute("srcset")
            jpg_url = re.findall(r"(https://.*?.jpg)", jpg_url_list)[-2]

            title_item = item.find_element_by_css_selector(
                "[class ^= 'ProductGridItem__title__']")
            produce_url = title_item.get_attribute("href")
            produce_name = title_item.text

            price_item = item.find_element_by_css_selector(
                "[class ^= 'ProductGridItem__price__']")
            price_value = price_item.find_element_by_xpath(
                "./span").get_attribute("aria-label")

            product["productName"] = produce_name
            product["productPrice"] = price_value
            product["productUrl"] = produce_url
            product["productImageUrl"] = jpg_url
            product["productImageName"] = downloadImage.format_img_name(
                name=produce_name)
            product["productMore"] = self.__open_new_windows(produce_url)

            logger.debug("Item: %s" % product)
            # yield jpg_url, produce_name, price_value, produce_url
            yield product

    def roll_to_top(self):
        num = 500
        while True:
            js = "var q=document.documentElement.scrollTop=%s" % num
            self.driver.execute_script(js)
            if num >= 10000:
                break
            num += 500
            time.sleep(1)

    def get_all_items(self, format=None):
        get_info = self.get_info_from_page_fmt1
        if format == 2:
            get_info = self.get_info_from_page_fmt2

        while True:
            for info in get_info():
                yield info
            self.driver.switch_to_window(self.main_windows_id)
            next_button_item = self.driver.find_elements_by_css_selector(
                "[class='a-last']")
            logger.debug("check have next page? : %s " % len(next_button_item))
            if next_button_item:
                next_button_item[-1].click()
            else:
                break
        self.driver.close()

    def __open_new_windows(self, url):
        js = "window.open('%s');" % url
        self.driver.execute_script(js)
        js = "var q=document.documentElement.scrollTop=1000"
        self.driver.execute_script(js)
        self.driver.implicitly_wait(10)
        self.driver.switch_to_window(self.driver.window_handles[-1])
        productOverview_content = self.driver.find_element_by_id(
            "productOverview_feature_div").text
        logger.debug(productOverview_content)
        self.driver.close()
        self.driver.switch_to_window(self.main_windows_id)
        return productOverview_content
